/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mvc;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.json.JsonObject;

/**
 *
 * @author William
 */
public abstract class FrontController extends Controller {

    private Map<String, View> views;
    private Set<String> remoteCalls;
    private String serverAddress;

    public FrontController(String name) {
        super(name);
        this.views = new HashMap();
        this.remoteCalls = new HashSet();
        this.serverAddress = "localhost";
    }

    //Getters and Setters
    public void setServer(String address) {
        this.serverAddress = address;
    }

    public String getServer() {
        return this.serverAddress;
    }

    //Collections methods
    public void registerRemoteCall(String callName) {
        this.remoteCalls.add(callName);
    }

    public void removeRemoteCall(String callName) {
        this.remoteCalls.remove(callName);
    }

    public void registerView(View v) {
        this.views.put(v.getName(), v);
    }

    public void removeView(String name) {
        this.views.remove(name);
    }

    //Other methods
    public abstract View createView(String viewName);

    public boolean evoke(String eventName, String callerName, JsonObject params) {
        Event evt = super.events.get(eventName);
        if (evt != null) {
            return evt.handle(params);
        }
        try {
            evt = (Event) Naming.lookup("//" + this.serverAddress + "/" + eventName);
            if(evt != null) {
                return evt.handle(params);
            }
            return false;
        } catch (NotBoundException | MalformedURLException | RemoteException ex) {
//            Logger.getLogger(FrontController.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }
    
    public JsonObject require(String resourceName, String callerName, JsonObject params ) {
        Resource rsc = super.resources.get(resourceName);
        if(rsc != null) {
            return rsc.obtain(params);
        }
        try {
            rsc = (Resource) Naming.lookup("//" + this.serverAddress + "/" + resourceName);
            if(rsc != null) {
                return rsc.obtain(params);
            }
            return null;
        } catch (NotBoundException | MalformedURLException | RemoteException ex) {
//            Logger.getLogger(FrontController.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
}
